<template>
	<view class="container">
		<!-- 表单内容 -->
		<view class="form-container">
			<!-- 申请人 -->
			<view class="form-section" style="margin-top: 0;">
				<view class="section-header">
					<text class="section-title">申请人</text>
				</view>
				<view class="section-content">
					<text class="applicant-name">{{username}}</text>
				</view>
			</view>

			<!-- 申请类型 - u-picker弹框选择 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">申请类型</text>
				</view>
				<view class="section-content b-r" @click="showTypePicker = true">
					<u-input v-model="selectedTypeLabel" placeholder="请选择审批类型" disabled
						class="type-select-input" style="pointer-events: none;"></u-input>
					<u-icon name="arrow-down" size="24" color="#c0c4cc"></u-icon>
				</view>
			</view>

			<!-- 申请内容 - 文本输入框 -->
			<view class="form-section" v-if="selectedType != 4 ">
				<view class="section-header">
					<text class="section-title">申请内容</text>
				</view>
				<view class="section-content">
					<u-textarea v-model="applyContent" placeholder="请输入申请内容" height="80"
						class="content-textarea"></u-textarea>
				</view>
			</view>

			<!-- 时间 -->
			<view class="form-section" v-if="selectedType == 3">
				<view class="section-header">
					<text class="section-title">任务开始时间</text>
				</view>
				<view class="section-content">
					<uni-datetime-picker type="datetime" v-model="startTime" @change="changeLog" />
				</view>
			</view>
			<view class="form-section" v-if="selectedType == 3">
				<view class="section-header">
					<text class="section-title">任务结束时间</text>
				</view>
				<view class="section-content">
					<uni-datetime-picker type="datetime" v-model="endTime" @change="changeLog" />
				</view>
			</view>

			<!-- 申请事由 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">申请事由</text>
				</view>
				<view class="section-content">
					<u-textarea v-model="applyReason" placeholder="请输入申请事由" height="80"></u-textarea>
				</view>
			</view>

			<!-- 新增：转移人选择区域 -->
			<view class="form-section" v-if="selectedType == 4">
				<view class="section-header">
					<text class="section-title">转移人</text>
					<!-- <text class="required-mark">*</text> -->
				</view>
				<view class="section-content">
					<!-- 已选转移人列表 -->
					<view class="transfer-list" v-if="transferPersons.length > 0">
						<view v-for="(person, index) in transferPersons" :key="person.id" class="transfer-item">
							<u-avatar :src="person.avatar" size="32"></u-avatar>
							<text class="transfer-name">{{ person.name }}</text>
							<u-icon name="close-circle" size="20" color="#ff4d4f"
								@click="removeTransferPerson(index)"></u-icon>
						</view>
					</view>
					<!-- 添加按钮 -->
					<view class="add-transfer-btn" @click="confirmTransferPersons" v-if="transferPersons.length < 1">
						<u-icon name="plus" size="24" color="#0057b8"></u-icon>
						<text class="add-text">添加转移人</text>
					</view>
				</view>
			</view>

			<!-- 说明附件 -->
			<view class="form-section">
				<view class="section-header">
					<text class="section-title">说明附件</text>
				</view>
				<view class="section-content">
					<u-upload :fileList="fileList" @afterRead="afterRead" multiple maxCount="5" :previewFullImage="true"
						@delete="deletePic"></u-upload>
				</view>
			</view>

			<!-- 审批流程 -->
			<view class="form-section">
				<view class="section-header section-header2">
					<text class="section-title">审批流程</text>
					<text class="section-subtitle">已由管理员预设不可修改审批人和删除抄送人</text>
				</view>

				<!-- 审批人 -->
				<view class="approval-section">
					<view class="approval-header">
						<text class="approval-title">审批人</text>
					</view>
					<view class="approval-list">
						<view v-for="(approver, index) in approvers" :key="index" class="approver-item">
							<u-avatar :src="approver.avatar" size="32"></u-avatar>
							<text class="approver-name">{{ approver.nickName }}</text>
						</view>
					</view>
				</view>

				<!-- 抄送人 -->
				<view class="approval-section">
					<view class="approval-header">
						<text class="approval-title">抄送人</text>
					</view>
					<view class="approval-list">
						<view v-for="(cc, index) in ccPersons" :key="index" class="approver-item">
							<u-avatar :src="cc.avatar" size="32"></u-avatar>
							<text class="approver-name">{{ cc.nickName }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<u-button class="submit-btn" type="primary"
				:custom-style="{ backgroundColor: '#0057b8', borderColor: '#0057b8' }"
				@click="submitApply">提交</u-button>
		</view>


		
		<!-- 申请类型选择弹框 -->
		<u-picker :show="showTypePicker" :columns="applyTypeColumns" keyName="label" :showToolbar="true"
			:closeOnClickOverlay="true" :safeAreaInsetBottom="true" @confirm="onTypeConfirm"
			@cancel="showTypePicker = false" @close="showTypePicker = false"></u-picker>


		

	</view>
</template>

<script>
	import {
		addMyTasksSp1,
		selectPerformanceLog,
		updateMyTasksSp1,
		selectTasksSpCcRecipient,
		selectTasksHbApprover
	} from '@/common/api/renwu.js'
	import {
		http
	} from '@/common/http.js';
	export default {
		data() {
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth();
			const day = now.getDate();
			return {
				username: '',
				value1: 0,
				// 申请类型相关
				showTypePicker: false,
				selectedType: '',
				selectedTypeLabel: '',
				applyTypeColumns: [
					[{
							label: '任务目标',
							value: '1'
						},
						{
							label: '任务内容',
							value: '2'
						},
						{
							label: '任务时间',
							value: '3'
						},
						{
							label: '任务转移',
							value: '4'
						}
					]
				],

				// 表单内容
				applyContent: '',
				applyReason: '',
				fileList: [],

				// 审批流程相关
				approvers: [],
				ccPersons: [],

				// 新增：转移人相关
				showTransferPicker: false, // 转移人选择弹框
				transferSearch: '', // 转移人搜索关键词
				transferPersons: [], // 已选转移人

				// 任务时间
				startTime: '',
				endTime: '',

				performance: {}

			}
		},

		created(options) {
			// this.username = uni.getStorageSync('userName')
			// this.performance = {
			// 	type: options.type,
			// 	phase: options.phase,
			// 	task_id: options.task_id
			// }
			this.getRecipientApprover()
		},

		methods: {
			// 抄送人  审批人
			async getRecipientApprover() {
				try {
					const res = await selectTasksSpCcRecipient({
						id: this.performance.task_id,
						phase: this.performance.phase,
					})
					console.log(res)
					this.ccPersons = res.data.ccRecipientList
					this.approvers = res.data.approvalList
				} catch (error) {
					//TODO handle the exception
				}
			},

			// 日期格式化
			formatter(type, value) {
				if (type === 'year') return `${value}年`;
				if (type === 'month') return `${value}月`;
				if (type === 'day') return `${value}日`;
				return value;
			},

			changeLog(e) {
				console.log('change事件:', e);
			},

			// 申请类型选择确认
			onTypeConfirm(e) {
				const selected = e.value[0]
				this.selectedType = selected.value
				this.selectedTypeLabel = selected.label
				this.showTypePicker = false
			},

			// 文件上传相关
			async afterRead(event) {
				let lists = [].concat(event.file);
				const fileKeys = []; // 存储每个文件的唯一key

				// 1. 先添加文件到列表，同时记录每个文件的key
				lists.forEach((item, index) => {
					const uniqueKey = Date.now() + '-' + index; // 更稳定的唯一标识（时间戳+索引）
					fileKeys.push(uniqueKey); // 存储key
					this.fileList.push({
						...item,
						status: "uploading",
						message: "上传中",
						key: uniqueKey // 存入key
					});
				});

				// 2. 逐个上传
				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);
						// 用预存的key查找，确保精准匹配
						const targetIndex = this.fileList.findIndex(item => item.key === fileKeys[i]);
						if (targetIndex !== -1) {
							this.fileList.splice(targetIndex, 1, {
								...this.fileList[targetIndex],
								status: "success",
								message: "",
								url: result
							});
						}
					} catch (err) {
						// 用预存的key查找失败的文件并删除
						const targetIndex = this.fileList.findIndex(item => item.key === fileKeys[i]);
						if (targetIndex !== -1) {
							this.fileList.splice(targetIndex, 1); // 移除失败文件
						}
						uni.showToast({
							title: `图片上传失败: ${err.message || '网络错误'}`,
							icon: 'none'
						});
					}
				}
			},
			// 上传文件（修改uploadFilePromise方法，明确抛出错误）
			async uploadFilePromise(url) {
				console.log('开始上传图片');
				try {
					uni.showLoading({
						title: '上传中...',
						mask: true
					});
					// 调用上传接口（假设http.upload会返回图片URL，失败则抛出错误）
					const res = await http.upload('/wx/performance/addEvidence', url);
					console.log(res, 't')
					uni.hideLoading();
					if (!res) {
						throw new Error('上传接口返回空数据');
					}
					return res; // 返回图片URL
				} catch (err) {
					uni.hideLoading();
					console.error('上传失败:', err);
					// 明确抛出错误，让上层afterRead捕获
					throw err;
				}
			},

			// 删除图片
			deletePic(event) {
				this[`fileList`].splice(event.index, 1);
			},

			// 新增：转移人相关方法
			// 检查转移人是否已选中
			isTransferSelected(id) {
				return this.transferPersons.some(person => person.id === id);
			},

			// 切换转移人选中状态
			toggleTransferPerson(person) {
				const index = this.transferPersons.findIndex(item => item.id === person.id);
				if (index > -1) {
					// 已选中则移除
					this.transferPersons.splice(index, 1);
				} else {
					// 未选中则添加
					this.transferPersons.push(person);
				}
			},

			// 移除已选转移人
			removeTransferPerson(index) {
				this.transferPersons.splice(index, 1);
			},

			// 确认选择转移人
			confirmTransferPersons() {
				uni.navigateTo({
					url: '/homeNav/customer/customer'
				})
			},

			// 表单验证（新增转移人验证）
			validateForm(isDraft = false) {
				if (!isDraft) {
					if (!this.selectedType) {
						uni.showToast({
							title: '请选择申请类型',
							icon: 'none'
						});
						return false;
					}
					if (!this.applyContent.trim()) {
						uni.showToast({
							title: '请输入申请内容',
							icon: 'none'
						});
						return false;
					}
					if (!this.applyReason.trim()) {
						uni.showToast({
							title: '请输入申请事由',
							icon: 'none'
						});
						return false;
					}
					// 新增：验证转移人
					if (!this.selectedType && this.transferPersons.length === 0) {
						uni.showToast({
							title: '请选择转移人',
							icon: 'none'
						});
						return false;
					}
				}
				return true;
			},

			// 提交申请
			submitApply() {
				if (!this.validateForm()) return;

				uni.showModal({
					title: '确认提交',
					content: '确定要提交申请吗？',
					success: (res) => {
						if (res.confirm) {
							this.handleSubmit();
						}
					}
				})
			},

			// 处理提交
			async handleSubmit() {
				uni.showLoading({
					title: '提交中...'
				});

				// 构造包含转移人的表单数据
				const formData = {
					...this.getFormData()
					
				};
				console.log('提交数据:', formData);
				try {
					let res = await addMyTasksSp1(formData)
					console.log(res, '----审批')
					uni.hideLoading();
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					setTimeout(() => uni.navigateBack(), 1500);
				} catch (error) {
					//TODO handle the exception
				}

			},

			// 获取表单数据
			getFormData() {
				let url = this.fileList.map(item => item.url)
				let approvers = this.approvers.map(item => item.userId).join()
				let ccPersons = this.ccPersons.map(item => item.userId).join()
				let transferPersons = this.transferPersons.map(item => item.userId).join()
				return {
					tasksId:this.performance.task_id,
					taskType:this.performance.phase,
					auditType: this.selectedType,
					// applyTypeLabel: this.selectedTypeLabel,
					content: this.applyContent,
					reason: this.applyReason,
					url: url.join(),
					approvers: approvers,
					ccPersons: ccPersons,
					transferId: transferPersons // 新增转移人数据
				}
			},


		}
	}
</script>

<style lang="scss" scoped>
	/* 原有样式保持不变，新增以下样式 */
	.container {
		min-height: 100vh;
		background-color: #f5f7fa;
		// padding-bottom: 120rpx;
	}

	.page-header {
		padding: 30rpx 32rpx;
		background: linear-gradient(135deg, #2979ff 0%, #1e62d9 100%);

		.page-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #ffffff;
		}
	}

	.form-container {
		// padding: 0 32rpx;
	}

	.form-section {
		background: #ffffff;
		// border-radius: 16rpx;
		margin-top: 24rpx;
		padding: 24rpx 32rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;


			.section-title {
				font-size: 28rpx;
				font-weight: 600;
				color: #303133;
			}

			.section-subtitle {
				font-size: 24rpx;
				color: #909399;
			}
		}

		.section-header2 {
			position: relative;
			/* 关键：让伪元素相对标题定位 */
			padding-left: 20rpx;
			/* 给竖线和文字之间留间距 */
		}

		/* 左侧竖线 */
		.section-header2::before {
			content: '';
			/* 伪元素必须有 content */
			position: absolute;
			/* 绝对定位，相对于标题 */
			left: 0;
			/* 靠左对齐 */
			top: 50%;
			/* 垂直居中 */
			transform: translateY(-50%);
			/* 精确居中（抵消自身高度的一半） */
			width: 4px;
			/* 竖线宽度 */
			height: 24px;
			/* 竖线高度（可根据标题文字大小调整） */
			background-color: #2979ff;
			/* 竖线颜色（示例用红色） */
			border-radius: 2px;
			/* 可选：给竖线加圆角 */
		}

		.section-content {
			display: flex;

			.applicant-name {
				font-size: 28rpx;
				color: #606266;
			}
		}
	}

	.b-r {
		border: 2rpx solid #dadbde;
		border-radius: 12rpx;
	}

	// 申请类型选择框样式
	.type-select-input {
		border: none !important;
		background-color: #ffffff !important;

		::v-deep .u-input {
			// border-radius: 12rpx;
			padding: 20rpx 24rpx;

			.u-input__content__field-wrapper__field {
				color: #606266;
				font-size: 28rpx;
			}

			.u-input__content__field-wrapper__placeholder {
				color: #c0c4cc;
				font-size: 28rpx;
			}

			.u-input__content__field-wrapper {
				min-height: auto;
			}
		}
	}

	// 申请内容文本域样式
	.content-textarea {
		::v-deep .u-textarea {
			border: 1rpx solid #dcdfe6;
			border-radius: 12rpx;
			padding: 20rpx;

			.u-textarea__field {
				font-size: 28rpx;
				color: #606266;
			}

			.u-textarea__field--placeholder {
				color: #c0c4cc;
				font-size: 28rpx;
			}
		}
	}

	.approval-section {
		margin-top: 32rpx;

		.approval-header {
			margin-bottom: 20rpx;

			.approval-title {
				font-size: 28rpx;
				font-weight: 500;
				color: #303133;
			}
		}

		.approval-list {
			display: flex;
			flex-flow: wrap;
			gap: 24rpx;


			.approver-item {
				display: flex;
				align-items: center;
				padding: 8rpx;
				border-radius: 8rpx;
				border: 1rpx solid #f0f0f0;

				&:last-child {
					border-bottom: none;
				}

				.approver-name {
					font-size: 24rpx;
					color: #303133;
					margin-left: 20rpx;
					margin-right: 16rpx;
				}

				.approver-role {
					font-size: 22rpx;
					color: #909399;
				}
			}
		}
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 20rpx 32rpx;
		border-top: 1rpx solid #e4e7ed;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
	}

	.safe-area-inset-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.action-buttons {
		display: flex;
		gap: 20rpx;

		.action-btn {
			flex: 1;
			height: 80rpx;
			border-radius: 12rpx;
			font-size: 28rpx;
			font-weight: 500;

			&.save-btn {
				background: #f5f7fa;
				color: #606266;
				border: 1rpx solid #dcdfe6;
			}

			&.submit-btn {
				background: linear-gradient(135deg, #2979ff 0%, #1e62d9 100%);
				color: #ffffff;
				border: none;
			}
		}
	}

	/* 自定义uView组件样式 */
	::v-deep .u-textarea {
		border: 1rpx solid #dcdfe6;
		border-radius: 12rpx;
		padding: 20rpx;
	}

	::v-deep .u-upload {
		margin-top: 0;
	}

	/* u-picker样式优化 */
	::v-deep .u-picker {
		.u-picker__toolbar {
			height: 96rpx;
			border-bottom: 1rpx solid #e4e7ed;

			.u-picker__toolbar__cancel,
			.u-picker__toolbar__confirm {
				font-size: 30rpx;
				padding: 0 32rpx;
			}

			.u-picker__toolbar__cancel {
				color: #909399;
			}

			.u-picker__toolbar__confirm {
				color: #2979ff;
			}
		}

		.u-picker__columns {
			.u-picker-column {
				.u-picker-column__item {
					font-size: 30rpx;
					color: #606266;
					height: 80rpx;
					line-height: 80rpx;

					&.u-picker-column__item--active {
						color: #2979ff;
						font-weight: 500;
					}
				}
			}
		}
	}

	/* 遮罩层样式 */
	::v-deep .u-popup {
		.u-popup__content {
			border-radius: 24rpx 24rpx 0 0;
		}
	}

	.submit-btn {
		width: 70%;
		margin: 36rpx auto;
		height: 88rpx;
		border-radius: 8rpx;
	}

	/* 转移人选择区域样式 */
	.required-mark {
		color: #ff4d4f;
		margin-left: 8rpx;
	}

	.transfer-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-bottom: 16rpx;
	}

	.transfer-item {
		display: flex;
		align-items: center;
		background-color: #f5f7fa;
		border-radius: 6rpx;
		padding: 8rpx 16rpx;
	}

	.transfer-name {
		font-size: 26rpx;
		color: #333;
		margin: 0 12rpx;
	}

	.add-transfer-btn {
		display: flex;
		align-items: center;
		width: 100%;
		padding: 20rpx;
		border: 2rpx dashed #c0c4cc;
		border-radius: 12rpx;
		color: #0057b8;
		font-size: 28rpx;
		box-sizing: border-box;
	}

	.add-text {
		margin-left: 12rpx;
	}

	/* 转移人选择弹框样式 */
	.transfer-popup {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.transfer-search {
		padding: 0 30rpx 16rpx;
	}

	.transfer-scroll {
		flex: 1;
		padding: 10rpx 0;
	}

	.transfer-option {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.transfer-option.selected {
		background-color: #f0f7ff;
	}

	.option-info {
		margin-left: 20rpx;
		flex: 1;
	}

	.option-name {
		font-size: 28rpx;
		color: #333;
	}

	.option-department {
		font-size: 24rpx;
		color: #999;
		display: block;
		margin-top: 4rpx;
	}

	.confirm-transfer-btn {
		margin: 20rpx 30rpx;
		height: 90rpx;
		font-size: 28rpx;
	}




	.approval-list-page {
		// min-height: 100vh;
		max-height: calc(100vh - 240rpx); // 减去导航、筛选和底部按钮高度
		background-color: #f5f7fa;
		// padding-bottom: 120rpx; // 预留底部按钮空间
	}

	// 搜索栏样式
	.search-container {
		padding: 16rpx 20rpx;
		background-color: #fff;
	}

	// 筛选栏样式
	.filter-bar {
		display: flex;
		padding: 0 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #eee;
	}

	.filter-item {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		margin-right: 10rpx;
		cursor: pointer;

		.filter-text {
			font-size: 28rpx;
			color: #333;
			margin-right: 8rpx;
		}
	}

	// 筛选弹窗样式
	.filter-popup {
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	.filter-option {
		padding: 20rpx 30rpx;
		font-size: 26rpx;
		color: #666;
		text-align: center;

		&:hover {
			background-color: #f5f5f5;
		}

		&.active {
			background-color: #e6f7ff;
			color: #0057b8;
			font-weight: 500;
		}
	}

	// 任务列表样式
	.task-list {
		height: calc(100vh - 280rpx); // 减去导航、筛选和底部按钮高度
	}

	.task-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx 30rpx;
		margin: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		transition: transform 0.2s;

		&:active {
			transform: scale(0.99);
		}
	}

	.task-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;

		.task-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
			max-width: 70%;
			line-height: 1.4;
		}
	}

	.task-info {
		.info-row {
			display: flex;
			margin-bottom: 12rpx;

			.info-label {
				font-size: 26rpx;
				color: #999;
				// min-width: 120rpx;
			}

			.info-value {
				font-size: 26rpx;
				color: #666;
				flex: 1;
			}
		}

		.info-row:last-child {
			margin-bottom: 0;
		}
	}

	// 空状态样式
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 150rpx 0;

		.empty-text {
			font-size: 30rpx;
			color: #999;
			margin-top: 30rpx;
		}

		.empty-desc {
			font-size: 26rpx;
			color: #ccc;
			margin-top: 15rpx;
		}
	}

	// 加载更多样式
	.load-more,
	.no-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 26rpx;
	}

	.loading-text {
		margin-left: 15rpx;
	}
</style>